package com.bestcem.xm.qdes.grpc.client;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.qdes.convert.grpc.QdesGrpcConvertMapper;
import com.bestcem.xm.qdes.grpc.client.dto.SurveyRespondentDto;
import com.bestcem.xm.survey.grpc.v1.services.*;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class SurveyGrpcClient {


    @GrpcClient(GrpcClientNames.DS_SURVEY)
    private BaseSurveyServiceGrpc.BaseSurveyServiceBlockingStub baseStub;

    @GrpcClient(GrpcClientNames.DS_SURVEY)
    private BpSurveyServiceGrpc.BpSurveyServiceBlockingStub stub;

    private final QdesGrpcConvertMapper grpcConvertMapper;

    public SurveyGrpcClient(QdesGrpcConvertMapper grpcConvertMapper) {
        this.grpcConvertMapper = grpcConvertMapper;
    }

    public List<QuotaCondition> getQuotaConditions(List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return null;
        }
        ListQuotaConditionByIdsRequest.Builder builder = ListQuotaConditionByIdsRequest.newBuilder();
        builder.addAllIds(ids);
        try {
            QuotaConditionSearchResponse response = baseStub.listQuotaConditionByIds(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[Qdes] getQuotaConditions, ids = {} Error; ErrorMsg: {}", ids, response);
                return null;
            }
            return response.getQuotaConditionListList();
        } catch (Exception e) {
            log.error("[Qdes] exp getQuotaConditions, ids = {} Error; ErrorMsg: {}", ids, e.getMessage(), e);
            return null;
        }
    }

    public String createSurveyQuota(String projectId, String quotaId, String checkNode, String name) {
        CreateQuotaConditionRequest.Builder builder = CreateQuotaConditionRequest.newBuilder();
        QuotaCondition.Builder cBuilder = QuotaCondition.newBuilder();
        cBuilder.setName(name);
        cBuilder.setQuotaId(quotaId);
        cBuilder.setProjectId(projectId);
        cBuilder.setCheckpoints(checkNode);
        builder.setQuotaCondition(cBuilder.build());
        try {
            CreateResponse response = baseStub.createQuotaCondition(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[qdes] createSurveyQuota Error, ErrorMsg: {}", response);
                return null;
            }
            return response.getId();
        } catch (Exception e) {
            log.error("[qdes] ex createSurveyQuota Error, ErrorMsg:", e);
            return null;
        }
    }

    public String createQuotaGidList(String quotaCondId, Integer qgid) {
        CreateQuotaConditionQgidListRequest.Builder builder = CreateQuotaConditionQgidListRequest.newBuilder();
        QuotaConditionQgidList.Builder cBuilder = QuotaConditionQgidList.newBuilder();
        cBuilder.setQuotaCondId(quotaCondId);
        cBuilder.setQgid(qgid);
        builder.setQuotaConditionQgidList(cBuilder.build());
        try {
            CreateResponse response = baseStub.createQuotaConditionQgidList(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[qdes] createQuotaGidList Error, ErrorMsg: {}", response);
                return null;
            }
            return response.getId();
        } catch (Exception e) {
            log.error("[qdes] ex createQuotaGidList Error, ErrorMsg:", e);
            return null;
        }
    }

    public String createQuotaCheckItem(String quotaCondId, String projectId, Integer num) {
        CreateQuotaCheckItemRequest.Builder builder = CreateQuotaCheckItemRequest.newBuilder();
        QuotaCheckItem.Builder cBuilder = QuotaCheckItem.newBuilder();
        cBuilder.setQuotaCondId(quotaCondId);
        cBuilder.setProjectId(projectId);
        cBuilder.setNum(num);
        builder.setQuotaCheckItem(cBuilder.build());
        try {
            CreateResponse response = baseStub.createQuotaCheckItem(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[qdes] createQuotaCheckItem Error, ErrorMsg: {}", response);
                return null;
            }
            return response.getId();
        } catch (Exception e) {
            log.error("[qdes] ex createQuotaCheckItem Error, ErrorMsg:", e);
            return null;
        }
    }

    public String createQuotaCheckItemOptionCombies(String qciId, String optionCombine) {
        CreateQuotaCheckItemOptionCombiesRequest.Builder builder = CreateQuotaCheckItemOptionCombiesRequest.newBuilder();
        QuotaCheckItemOptionCombies.Builder cBuilder = QuotaCheckItemOptionCombies.newBuilder();
        cBuilder.setQuotaCheckitemId(qciId);
        cBuilder.setOptionCombine(optionCombine);
        builder.setQuotaCheckItemOptionCombies(cBuilder.build());
        try {
            CreateResponse response = baseStub.createQuotaCheckItemOptionCombies(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[qdes] createQuotaCheckItemOptionCombies Error, ErrorMsg: {}", response);
                return null;
            }
            return response.getId();
        } catch (Exception e) {
            log.error("[qdes] ex createQuotaCheckItemOptionCombies Error, ErrorMsg:", e);
            return null;
        }
    }

    public String createQuotaCheckItemOptionList(String qciId, Integer ogid) {
        CreateQuotaCheckItemOptionListRequest.Builder builder = CreateQuotaCheckItemOptionListRequest.newBuilder();
        QuotaCheckItemOptionList.Builder cBuilder = QuotaCheckItemOptionList.newBuilder();
        cBuilder.setQuotaCheckitemId(qciId);
        cBuilder.setOgid(ogid);
        builder.setQuotaCheckItemOptionList(cBuilder.build());
        try {
            CreateResponse response = baseStub.createQuotaCheckItemOptionList(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[qdes] createQuotaCheckItemOptionList Error, ErrorMsg: {}", response);
                return null;
            }
            return response.getId();
        } catch (Exception e) {
            log.error("[qdes] ex createQuotaCheckItemOptionList Error, ErrorMsg:", e);
            return null;
        }
    }

    public void genQuotaNumDelay(String projectId, String quotaId) {
        GenQuotaNumRequest.Builder builder = GenQuotaNumRequest.newBuilder();
        builder.setQuotaId(quotaId);
        builder.setProjectId(projectId);
        try {
            GenQuotaNumResponse response = baseStub.genQuotaNum(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[qdes] genQuotaNumDelay Error, ErrorMsg: {}", response);
            }
        } catch (Exception e) {
            log.error("[qdes] ex genQuotaNumDelay Error, ErrorMsg:", e);
        }
    }

    public void refreshQuotaProgress(String quotaId) {
        RefreshQuotaProgressRequest.Builder builder = RefreshQuotaProgressRequest.newBuilder();
        builder.setQuotaId(quotaId);
        try {
            RefreshQuotaProgressResponse response = baseStub.refreshQuotaProgress(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[qdes] refreshQuotaProgress Error, ErrorMsg: {}", response);
            }
        } catch (Exception e) {
            log.error("[qdes] ex refreshQuotaProgress Error, ErrorMsg:", e);
        }
    }

    public Integer countSurveyQuota(String projectId, List<String> qgidList, Boolean isNormal) {
        // 这些题目被设置的次数
        int data = 0;
        CountQuotaConditionRequest.Builder builder = CountQuotaConditionRequest.newBuilder();
        builder.setProjectId(projectId);
        builder.addAllQgidList(qgidList);
        if (isNormal != null) {
            builder.addIsNormal(isNormal);
        }
        try {
            CountQuotaConditionResponse response = baseStub.countQuotaCondition(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[qdes] countSurveyQuota Error, ErrorMsg: {}", response);
                return null;
            }
            data = response.getCount();
        } catch (Exception e) {
            log.error("[qdes] ex countSurveyQuota Error, ErrorMsg:", e);
            return null;
        }
        return data;
    }

    public void surveyCreateCrossQuotaCondition(JSONObject param) {
        // 创建交叉配额
        CreateCrossQuotaRequest.Builder builder = CreateCrossQuotaRequest.newBuilder();
        builder.setProjectId(param.getString("projectId"));
        builder.setQuotaId(param.getString("quotaId"));
        builder.setCheckNode(param.getString("check_node"));
        builder.setRow1(param.getString("row1"));
        builder.setRow2(param.getString("row2"));
        builder.setCol1(param.getString("col1"));
        builder.setCol2(param.getString("col2"));
        builder.setCheckitemNums(param.getString("checkitem_nums"));
        builder.setAvaQgidList(param.getString("ava_qgid_list"));
        try {
            CreateCrossQuotaResponse response = baseStub.createCrossQuota(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[qdes] countSurveyQuota Error, ErrorMsg: {}", response);
            }
        } catch (Exception e) {
            log.error("[qdes] ex countSurveyQuota Error, ErrorMsg:", e);
        }
    }

    public void deleteSurveyQuotas(List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }
        DeleteQuotaConditionRequest.Builder builder = DeleteQuotaConditionRequest.newBuilder();
        builder.addAllIds(ids);
        try {
            DeleteResponse response = baseStub.deleteQuotaCondition(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[Qdes] deleteSurveyQuotas, ids = {} Error; ErrorMsg: {}", ids, response);
            }
        } catch (Exception e) {
            log.error("[Qdes] exp deleteSurveyQuotas, ids = {} Error; ErrorMsg: {}", ids, e.getMessage(), e);
        }
    }

    public void copySurveyQuotas(List<String> ids, String oldId, String newId) {
        if (CollectionUtils.isEmpty(ids) || StringUtils.isEmpty(oldId) || StringUtils.isEmpty(newId)) {
            return;
        }
        CopyQuotaConditionRequest.Builder builder = CopyQuotaConditionRequest.newBuilder();
        builder.addAllConditionIds(ids);
        builder.setNewId(newId);
        builder.setOldId(oldId);
        try {
            CopyQuotaConditionResponse response = baseStub.copyQuotaCondition(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[Qdes] copySurveyQuotas, ids = {} Error; ErrorMsg: {}", ids, response);
            }
        } catch (Exception e) {
            log.error("[Qdes] exp copySurveyQuotas, ids = {} Error; ErrorMsg: {}", ids, e.getMessage(), e);
        }
    }

    public void copyImportSurveyQuotas(List<String> ids, String projectId, String newQuotaId, String data) {
        if (CollectionUtils.isEmpty(ids) || StringUtils.isEmpty(projectId) || StringUtils.isEmpty(newQuotaId)) {
            return;
        }
        CopyImportQuotaConditionRequest.Builder builder = CopyImportQuotaConditionRequest.newBuilder();
        builder.addAllConditionIds(ids);
        builder.setData(data);
        builder.setNewQuotaId(newQuotaId);
        builder.setTargetProjectId(projectId);
        try {
            CopyImportQuotaConditionResponse response = baseStub.copyImportQuotaCondition(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[Qdes] copyImportSurveyQuotas, ids = {} Error; ErrorMsg: {}", ids, response);
            }
        } catch (Exception e) {
            log.error("[Qdes] exp copyImportSurveyQuotas, ids = {} Error; ErrorMsg: {}", ids, e.getMessage(), e);
        }
    }

    public List<String> getQuotaIdList(String projectId, List<String> qgids) {
        if (CollectionUtils.isEmpty(qgids) || StringUtils.isEmpty(projectId)) {
            return null;
        }
        GetQuotaIdListRequest.Builder builder = GetQuotaIdListRequest.newBuilder();
        builder.setProjectId(projectId);
        builder.addAllQgids(qgids);
        try {
            GetQuotaIdListResponse response = baseStub.getQuotaIdList(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[Qdes] getQuotaIdList, projectId = {}, qgids = {}, Error; ErrorMsg: {}", projectId, qgids, response);
            } else {
                return response.getIdsList();
            }
        } catch (Exception e) {
            log.error("[Qdes] exp getQuotaIdList, projectId = {}, qgids = {}, Error; ErrorMsg: {}", projectId, qgids, e.getMessage(), e);
        }
        return null;
    }

    public List<SurveyRespondentDto> listRespondent(JSONObject jsonObject) {
        if (ObjectUtil.isEmpty(jsonObject)) {
            return null;
        }
        ListRespondentRequest.Builder builder = ListRespondentRequest.newBuilder();
        Respondent respondent = Respondent.newBuilder()
                .setProjectId(jsonObject.getString("project_id"))
                .setDataStatusValue(jsonObject.getInteger("data_status"))
                .setStatusValue(jsonObject.getInteger("status")).build();
        builder.setRespondent(respondent);
        try {
            RespondentSearchResponse response = baseStub.listRespondent(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[Qdes] listRespondent, jsonObject = {} Error; ErrorMsg: {}", jsonObject, response);
                return null;
            }
            if (ObjectUtil.isEmpty(response.getRespondentListList())) {
                return new ArrayList<>();
            } else {
                return grpcConvertMapper.toSurveyRespondentDtoList(response.getRespondentListList());
            }
        } catch (Exception e) {
            log.error("[Qdes] exp listRespondent, jsonObject = {} Error; ErrorMsg: {}", jsonObject, e.getMessage(), e);
            return null;
        }
    }

    /**
     * 发布问卷/项目外部参数有关键改动时新建记录
     *
     * @param project_id
     * @param releaseVer
     * @author chenglong.yue <chenglong.yue@idiaoyan.com>
     * @date 2023/4/7 14:43
     */
    public void copyExtParam(String project_id, Integer releaseVer) {
        CopyExtParameterRequest.Builder builder = CopyExtParameterRequest.newBuilder();
        builder.setProjectId(project_id);
        builder.setReleaseVer(releaseVer);
        try {
            CopyExtParameterResponse response = baseStub.copyExtParameter(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[Qdes] copyExtParam, project_id = {},releaseVer = {} Error; ErrorMsg: {}", project_id, releaseVer, response);
            }
        } catch (Exception e) {
            log.error("[Qdes] exp copyExtParam, project_id = {},releaseVer = {} Error; ErrorMsg: {}", project_id, releaseVer, e.getMessage(), e);
        }
    }

    /**
     * 生成答卷数据列
     *
     * @param project_id
     * @param company_id
     * @author chenglong.yue <chenglong.yue@idiaoyan.com>
     * @date 2023/4/7 14:43
     */
    public void createColumnsRelsProject(String project_id, String company_id) {
        CreateColumnsRelsProjectRequest.Builder builder = CreateColumnsRelsProjectRequest.newBuilder();
        builder.setProjectId(project_id);
        builder.setCompanyId(company_id);
        try {
            CreateColumnsRelsProjectResponse response = baseStub.createColumnsRelsProject(builder.build());
            if (Objects.isNull(response) || response.getStatus().getCodeValue() != 0) {
                log.error("[Qdes] createColumnsRelsProject, project_id = {},company_id = {} Error; ErrorMsg: {}", project_id, company_id, response);
            }
        } catch (Exception e) {
            log.error("[Qdes] exp createColumnsRelsProject, project_id = {},company_id = {} Error; ErrorMsg: {}", project_id, company_id, e.getMessage(), e);
        }
    }
}
